package com.cloudjan.springcloud.controller;

import com.cloudjan.springcloud.entities.CommonResult;
import com.cloudjan.springcloud.entities.Payment;
import com.cloudjan.springcloud.service.PaymentService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import java.util.concurrent.TimeUnit;

@RestController
@Slf4j
public class PaymentController {
    @Autowired
    private PaymentService paymentService;

    @Value("${server.port}")
    private String serverport;

    @PostMapping(value = "/payment/create")
    public CommonResult create(@RequestBody Payment payment){
        int result = paymentService.create(payment);
        log.info("插入结果=={}",payment);
        if(result>0){
            return new CommonResult(200,"插入成功！serverport="+serverport,result);
        } else{
            return new CommonResult(444,"插入失败！");
        }
    }

    @GetMapping(value = "/payment/get/{id}")
    public CommonResult<Payment> get(@PathVariable("id") Long id){
        Payment result = paymentService.getPaymentById(id);
        log.info("查询的结果=={}",result);
        if(result!=null){
            return new CommonResult(200,"查询成功,serverport="+serverport,result);
        } else{
            return new CommonResult(444,"记录不存在，id={}"+id);
        }
    }

    /**
     * 用于测试自定义的轮询负载均衡算法
     * @return
     */
    @GetMapping("/payment/lb")
    public String getServerport(){
        return serverport;
    }

    /**
     * 测试feign超时时间
     * @return
     */
    @GetMapping("/payment/feign/timeout")
    public String paymentFeignTimeout(){
        try {
            TimeUnit.SECONDS.sleep(3);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return serverport;
    }
}
